package com.yyh.json;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Demo6 {
    public static void main(String[] args) throws IOException {
        //创建集合
        List<User> list = new ArrayList<User>();
        list.add(new User("张三",18,"男",new String[]{"看电影","看小说"}));
        list.add(new User("lisi",18,"男",new String[]{"打牌","看小说"}));
        list.add(new User("三三",7,"男",new String[]{"看电影","害羞"}));
        list.add(new User("力安",4,"男",new String[]{"看电影","装酷"}));
        //创建Jackson操作对象
        ObjectMapper mapper = new ObjectMapper();
        //将list集合转为JSON字符串
        String json = mapper.writeValueAsString(list);
        System.out.println(json);
        //将list集合转为json字符串并存入JacksonList.json文件中
        mapper.writeValue(new File("D:\\ideaproject\\IO-code\\XML-code\\src\\com\\yyh\\json\\JacksonList.json"),list);
        //将list集合对象转为字节数组
        byte[] bytes = mapper.writeValueAsBytes(list);
        System.out.println(new String(bytes));
        //将list集合对象的json字符串：json转为list集合对象
        JsonNode jsonNode = mapper.readTree(json);
        for (JsonNode node : jsonNode){
            System.out.println(node);
        }
        System.out.println("----------------------------------");
        //JacksonList.json文件中的list集合json字符串读出来，转为list集合对象
        JsonNode jsonNode1 = mapper.readTree(new File("D:\\ideaproject\\IO-code\\XML-code\\src\\com\\yyh\\json\\JacksonList.json"));
        for (JsonNode node : jsonNode1){
            System.out.println(node);
        }
        System.out.println("----------------------------------");
        //将bytes数组中的内容读出来转为对象
        JsonNode jsonNode2 = mapper.readTree(bytes);
        for (JsonNode node : jsonNode2){
            System.out.println(node);
        }

    }
}
